package com.wn.framework.manager

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle

/**
 * @Author: wn
 * @Date: 2024/8/13 15:45
 * @Description: Activity 生命周期管理 注册 监听
 * 1 程序 位于 前台 , 后台
 * 2 只针对当前 页面
 */
object ActivityLifecycle {
  /**
   * 打开的Activity数量统计
   */
  private var activityStartCount = 0

  /**
   * 注册 Activity 生命周期
   * @param application Application
   */
  fun register(application: Application) {
    application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {

      /**
       * 位于前台
       */
      override fun onActivityStarted(activity: Activity) {
        activityStartCount++
        if (activityStartCount == 1) {
          AppFrontBack.onFront(activity)
        }
      }

      /**
       * 位于后台
       */
      override fun onActivityStopped(activity: Activity) {
        activityStartCount--
        if (activityStartCount == 0) {
          AppFrontBack.onBack(activity)
        }
      }

      // 添加 Activity 到 list 中
      override fun onActivityCreated(activity: Activity, p1: Bundle?) {
        ActivityManager.push(activity)
      }

      // list 移除 Activity
      override fun onActivityDestroyed(activity: Activity) {
        ActivityManager.pop(activity)
      }

      override fun onActivityResumed(activity: Activity) {

      }

      override fun onActivityPaused(activity: Activity) {

      }

      override fun onActivitySaveInstanceState(activity: Activity, p1: Bundle) {

      }
    })
  }
}